<template>
  <ckeditor
    :id="ckeditorId"
    ref="refCKEditor"
    v-model="editorData"
    :config="editorConfig"
    :read-only="readOnly"
    :throttle="20"
    :editor-url="editorUrl"
    @namespaceloaded="onNamespaceLoaded"
    @ready="onEditorReady"
    @input="onEditorInput"
    class="newCkeditor"
    @blur="getBlur"
  />
</template>

<script>
import CKEditor from "ckeditor4-vue";
import imgPath from "@/utils/config";
export default {
  name: "CKEditor",
  components: {
    ckeditor: CKEditor.component, // 引入
  },
  props: {
    // 用于区分单个tinymce
    ckeditorId: {
      type: String,
      default: "ckeditor" + new Date().getTime() + parseInt(Math.random(20)),
    },
    value: {
      // 内容
      type: String,
      default: "",
    },
    readOnly: {
      // 只读状态（这里说明一下，CKEditor4没有禁用只有只读）
      type: Boolean,
      default: false,
    },
    height: {
      // 富文本高度
      type: String,
      default: '30vh',
    },
    toolbar: {
      // 富文本工具栏的相关配置，后续如果增加插件如果只是启用插件不配置工具栏也是不会出现该功能的
      type: Array,
      default: () => {
        return [
          {
            name: "document",
            items: [
              "Source",
              "-",
              "Save",
              "NewPage",
              "ExportPdf",
              "Preview",
              "Print",
              "-",
              "Templates",
            ],
          },
          {
            name: "clipboard",
            items: [
              "Cut",
              "Copy",
              "Paste",
              "PasteText",
              "PasteFromWord",
              "-",
              "Undo",
              "Redo",
            ],
          },
          {
            name: "editing",
            items: ["Find", "Replace", "-", "SelectAll", "-", "Scayt"],
          },
          {
            name: "forms",
            items: [
              "Form",
              "Checkbox",
              "Radio",
              "TextField",
              "Textarea",
              "Select",
              "Button",
              "ImageButton",
              "HiddenField",
            ],
          },
          "/",
          {
            name: "basicstyles",
            items: [
              "Bold",
              "Italic",
              "Underline",
              "Strike",
              "Subscript",
              "Superscript",
              "-",
              "CopyFormatting",
              "RemoveFormat",
            ],
          },
          {
            name: "paragraph",
            items: [
              "NumberedList",
              "BulletedList",
              "-",
              "Outdent",
              "Indent",
              "-",
              "Blockquote",
              "CreateDiv",
              "-",
              "JustifyLeft",
              "JustifyCenter",
              "JustifyRight",
              "JustifyBlock",
              "-",
              "BidiLtr",
              "BidiRtl",
              "Language",
            ],
          },
          { name: "links", items: ["Link", "Unlink", "Anchor"] },
          {
            name: "insert",
            items: [
              "Image",
              "Table",
              "HorizontalRule",
              "Smiley",
              "SpecialChar",
              "PageBreak",
              "Iframe",
            ],
          },
          "/",
          {
            name: "styles",
            items: ["Styles", "Format", "Font", "FontSize", "lineheight"],
          },
          { name: "colors", items: ["TextColor", "BGColor"] },
          { name: "tools", items: ["Maximize", "ShowBlocks"] },
        ];
      },
    },
    // 启动插件
    extraPlugins: {
      // 这里的插件主要是非自带的插件需要先在这里启用再添加到上边的工具里
      type: String,
      default: "lineheight",
    },
    data: {
      type: String,
      default: "",
    },
    // 删除工具栏的功能
    removeButtons: {
      // 一些不需要的功能可以在这里删除，主要是针对自带的功能，如果是非自带的直接不启动插件就好了
      type: String,
      default: "",
      // default: 'Source,Save,NewPage,ExportPdf,Preview,Print,Templates,Cut,Copy,Paste,PasteText,PasteFromWord,Undo,Redo,Replace,Find,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Subscript,Superscript,CopyFormatting,Outdent,Indent,CreateDiv,Blockquote,BidiLtr,BidiRtl,Language,Unlink,Link,Anchor,HorizontalRule,Smiley,SpecialChar,PageBreak,Iframe,Styles,ShowBlocks,About,Font'
    },
    autoGrowMinHeight: {
      type: Number,
      default: 200, // 自动增长最小高度,
    },
    autoGrowMaxHeight: {
      type: Number,
      default: 0, // 自动增长最大高度
    },
    editorplaceholder: {
      // 类似input的placeholder
      type: String,
      default: "1000字以内，如有详细材料，请另附",
    },
    // 上传图片地址
    imgUploadUrl: {
      // 这里是配置图片的上传地址，这里要写完整路径
      type: String,
      default: `${imgPath.imgPath}/common/upload/file`,
    },
    // 删除插件
    removePlugins: {
      // 主要是删除自带的付费插件，避免报错和警告
      type: String,
      default: "exportpdf,easyimage,cloudservices",
    },
  },
  data() {
    return {
      reportIndex: null,
      editorData: this.data,
      ckeditor: null,
      editorUrl: "/ckeditor/ckeditor.js", // 将指令的值更改为指向所需的 CKEditor 4 脚本位置来更改
      editorConfig: {
        image_previewText: "&nbsp;",
        removeDialogTabs: "image:advanced;image:Link;",
        contentsCss: [
          "/ckeditor/samples/css/samples.css",
          "/ckeditor/plugins/dialog/styles/dialog.css",
        ], // 配置样式相关的文件，如果有精力完全可以自定义全部样式
        language: "zh-cn",
        height: this.height,
        toolbar: this.toolbar,
        extraPlugins: this.extraPlugins,
        autoGrow_minHeight: this.autoGrowMinHeight,
        autoGrow_maxHeight: this.autoGrowMaxHeight,
        editorplaceholder: this.editorplaceholder,
        removeButtons: this.removeButtons,
        removePlugins: this.removePlugins,
        pasteFromWordRemoveFontStyles: true, // 保证word导入格式
        pasteFromWordRemoveStyles: false, // 粘贴从Word删除样式
        forcePasteAsPlainText: false, // 是否强制复制来的内容去除格式
        allowedContent: true, // 允许所有格式
        filebrowserImageUploadUrl: this.imgUploadUrl, // 上传地址
        on: {
          // 这里可以绑定一些方法获取到不同生命周期或不同时机触发的回调，具体根据自身需求查阅文档
          instanceReady: this.instanceReady, // 创建 CKEDITOR 实例、完全初始化并准备好交互时触发的事件。
        },
      },
      notError: true,
      num: 0,
    };
  },
  watch: {
    editorData() {
      this.$emit("update:data", this.editorData);
    },
    data(newV, oldV) {
      this.editorData = newV;
      // console.log(newV, oldV);
    },
  },
  methods: {
    getBlur() {
      const _this = this;
      const editor = _this.$refs.refCKEditor.instance;
      const contenr = editor.getData();
      this.$emit("update:data", contenr);
    },
    // 当编辑器加载成功后调用
    onNamespaceLoaded(CKEDITOR) {},
    instanceReady(evt) {
      const _this = this;
      const editor = _this.$refs.refCKEditor.instance;
      editor.on("paste", function (e) {
        var content = e.data.dataValue; // 粘贴的内容（字符串）
        // console.log(content);
        this.editorData = content;
        e.editor.document; // 获取富文本内容
      });
      editor.on("afterPaste", function (e) {});
      editor.on("instanceReady", function (e) {
        var items = e.data.$.clipboardData.items;
        console.log(items);
      });
    },

    // 触发上传事件
    onEditorReady() {
      const _this = this;
      const editor = _this.$refs.refCKEditor.instance;
      const upload = editor.uploadRepository;
      let fileInfo = {};
      upload.on("instanceCreated", (evt) => {
        this.num = 0;
        this.notError = true;
        const { file } = evt.data;
        fileInfo = file;
        const isLt1M = file.size / 1024 / 1024 < 2; // 小于1M
        const fileType = file.type.substring(
          file.type.lastIndexOf("/") + 1,
          file.type.length
        );
        const type =
          fileType == "jpg" ||
          fileType == "jpeg" ||
          fileType == "png" ||
          fileType == "JPG" ||
          fileType == "JPEG";
        if (!type) {
          _this.$message.error(
            "上传图片只能是jpg 、 jpeg 、 png 、 JPG 、 JPEG格式!"
          );
        } else if (!isLt1M) {
          _this.$message.error("上传失败，图片不可超过2MB!");
        }
        if (type && isLt1M) {
          this.notError = true;
        } else {
          this.notError = false;
          throw new Error("上传内容不符合条件!"); // 手动抛出异常可以解决手动多次上传按钮失效问题
        }
        this.num = 1;
      });
      editor.on("fileUploadRequest", (evt) => {
        const fileLoader = evt.data.fileLoader;
        const { xhr, file } = fileLoader;

        if (this.notError) {
          const formData = new FormData();
          xhr.open("post", this.imgUploadUrl);
          console.log("数据");
          formData.append("file", file);
          xhr.send(formData);
          evt.stop();
        }
        evt.stop();
        evt.cancel();
      });
      editor.on("fileUploadResponse", (evt) => {
        evt.stop();
        const xhr = evt.data.fileLoader.xhr;
        const res = JSON.parse(xhr.responseText);
        console.log(res);
        // 自己处理返回逻辑
        if (res.code == 200) {
          
          evt.data.url = res.data.url;
          console.log(evt.data.url);
        } else {
          this.$message.error(res.message);
          evt.cancel();
        }
      });
    },
    onEditorInput(e) {
      console.log(e);
      this.$emit("input", e);
      this.$emit("eventHandle", {
        type: "change",
        data: e,
        reportIndex: this.reportIndex,
      });
    },
    openSuccessTip(text) {
      this.$message({
        message: text,
        type: "success",
      });
    },
  },
};
</script>
<style lang="scss">
.el-message--error {
  z-index: 10011 !important;
}
/deep/ .cke_dialog_container {
  position: fixed;
  overflow-y: auto;
  overflow-x: auto;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10010;
}
::v-deep .cke_dialog_container {
  position: fixed;
  overflow-y: auto;
  overflow-x: auto;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10010;
}
</style>
